// 导入创建仓库模块
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
// 导入推断仓库类型 1.导入ts
import type { RootState } from "./index";

// 解密
import crypt from "@/utils/crypto";
// 这里是改模块的state的类型 2.实例

// 这里是改模块的state的类型 1.接口
interface User {
  user: UserObject;
  user_token: AccessToken;
  isLogin: boolean;
  wxInfo: wxInfo;
  openid:string;
}
interface AccessToken {
  access_token: string;
  expires_in: number;
  refresh_token: string;
  openid: string;
  scope: string;
  createdTime?: number;
  endTime?: number;
}

// 用户
interface UserObject {
  name?: string;
  sex?: number;
  birthday?: any;
  code?: number | string;
  mobile: string | number;
  plate_number?: string;
}

// 获取浏览器存储
// 默认值
const getUser = {
  access_token: "",
  expires_in: 2,
  refresh_token: "",
  openid: "",
  scope: "",
};
const wxInfo = {
    openid: "",
    nickname: "",
    sex: -1,
    headimgurl: "",
  }

const checkUserToken = (name:string) => {
  const encryptedUserToken = localStorage.getItem(name);

  if (encryptedUserToken) {
    const decryptedUserToken: AccessToken = JSON.parse(
      JSON.stringify(crypt.decrypt(encryptedUserToken))
    );
    console.log("解密的" + name, decryptedUserToken);
    // console.log("解密的 user_token.openid:", decryptedUserToken.openid);

    // 执行其他逻辑，如设置用户状态、重定向等
    // 是否过期，过期重新请求，否则跳转
    checkTime(encryptedUserToken);
    // window.location.href = 'http://mfmaef89.beesnat.com/index';
    return decryptedUserToken;
  }
  return getUser;
};
const checkWxInfo = (name: string) => {
  const encryptedUserToken = localStorage.getItem(name);

  if (encryptedUserToken) {
    const decryptedUserToken: AccessToken = JSON.parse(
      JSON.stringify(crypt.decrypt(encryptedUserToken))
    );
    console.log("解密的" + name, decryptedUserToken);
    // console.log("解密的 user_token.openid:", decryptedUserToken.openid);
    return decryptedUserToken;
  }
  return wxInfo;
};

const checkOpenId = (name?: string) => {
  const encryptedUserToken = localStorage.getItem("phoneOpenid");

  if (encryptedUserToken) {
    const decryptedUserToken: { openid: string } = JSON.parse(
      JSON.stringify(crypt.decrypt(encryptedUserToken))
    );
    console.log("解密的" + name, decryptedUserToken);
    // console.log("解密的 user_token.openid:", decryptedUserToken.openid);
    return decryptedUserToken;
  }
  return {openid:""};
};

  // 校验access_token是否过期
const checkTime = (encryptedUserToken: any) => {
    // 获取本地时间
    const isTime = isTokenValid(encryptedUserToken);
    // 有效期内
    if (isTime) {
      // this.getInfo(access_token)
      console.log("有效期内");
      // console.log(UserToken, "UserToken");
      // 跳转首页
      return true;
    } else {
      // 重新获取
      console.log("重新获取");
      
      return false;
    }
  };

  // 判断是否在有效期内，后期后端做
  const isTokenValid = (encryptedUserToken: any) => {
    const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
    console.log(encryptedUserToken, "encryptedUserToken");
    // console.log(currentTime, "currentTime");
    const expirationTime = 7200 + encryptedUserToken.createdTime; // 过期时间戳
    // console.log(expirationTime, "expirationTime");
    return currentTime < expirationTime;
  };
// 这里是改模块的state的类型 2.实例
const user_token: User = {
  user_token: checkUserToken("encryptedUserToken"),
  user: {
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    code: "",
    plate_number: "",
  },
  wxInfo: {
    openid: "",
    nickname: "",
    sex: -1,
    headimgurl: "",
  },
  isLogin: false,
  openid: checkOpenId().openid,
};

// 实例模块
const systemSlice = createSlice({
  //模块命名
  name: "systemSlice",
  //初始值 // 3.使用
  initialState: user_token,
  //方法
  reducers: {
    // changeUserToken(state, params) {
    //   state.openid = params.payload
    // },
    // 使用PayloadAction类型来接收整个对象
    changeUserToken(state, action: PayloadAction<AccessToken>) {
      // 直接将整个对象赋值给state
      state.user_token = action.payload;
    },

    changeWxInfo(state, action: PayloadAction<wxInfo>) {
      // 直接将整个对象赋值给state
      state.wxInfo = action.payload;
    },
    // changeUser(state, params) {
    //   state.user = params;
    // },
    changeUser(state, action: PayloadAction<UserObject>) {
      // 直接将整个对象赋值给state
      state.user = action.payload;
    },
    changeIsLogin(state) {
      state.isLogin = !state.isLogin;
    },
    changeOpenid(state, params) {
      state.openid = params.payload;
    },
  },
});

// 导出方法
export const {
  changeUserToken,
  changeIsLogin,
  changeUser,
  changeWxInfo,
  changeOpenid,
} = systemSlice.actions;

// 导入推断仓库类型 2.使用ts
// 方便使用者去使用state
// 导出属性
export const myUserToken = (state: RootState) => state.user.user_token;
export const storeIsLogin = (state: RootState) => state.user.isLogin;
export const storeUser = (state: RootState) => state.user.user;
export const myWxInfo = (state: RootState) => state.user.wxInfo;
export const phoneOpenid = (state: RootState) => state.user.openid;
export default systemSlice.reducer;
